package com.tool.bloomFilter;

import com.google.common.hash.BloomFilter;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author 酒徒
 * @Version 1.0
 * @data 2025/4/14 11:37
 */
@Component
public class RedisBloomFilter {
    private static final int EXPECTED_ELEMENTS = 100;
    private static final double FALSE_POSITIVE_PROBABILITY = 0.01;
    private RBloomFilter<Integer> bloomFilter;


    @PostConstruct
    public void Init() {
        String key = "REDIS_BLOOM_FILTER";
        //测试类中指定了加载类
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://localhost:6379");
        RedissonClient redissonClient = Redisson.create(config);
        bloomFilter = redissonClient.getBloomFilter(key);
        bloomFilter.tryInit(EXPECTED_ELEMENTS, FALSE_POSITIVE_PROBABILITY);
    }

    public void addElement(Integer element) {
        bloomFilter.add(element);
    }

    public boolean mightContain(Integer element) {
        return bloomFilter.contains(element);
    }
}
